//@ts-nocheck
import React, { useEffect, useImperativeHandle } from 'react'

import * as echarts from 'echarts/lib/echarts'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/grid'
import 'echarts/lib/chart/bar'
import { Option, ChartsInstance } from '../Bar/interface'

import './index.less'

let echartsInstance: any
let data: Array<Option> = []

interface IProps {
  chartId?: string
  options?: Array<Option>
  chartRef?: React.MutableRefObject<ChartsInstance>
  seriesName?: string
  data?: any
}

const CrossMultiBarChart: React.FC<IProps> = ({
  options,
  chartId,
  chartRef,
  seriesName = '',
  data
}) => {
  useEffect(() => {
    echartsInstance = echarts.init(
      document.getElementById(chartId || 'strip-cross-multi-bar-chart')
    )
    setOptions()
  }, [])

  useEffect(() => {
    data = options
    if (echartsInstance) setOptions()
  }, [options])

  useImperativeHandle(chartRef, () => ({
    getInstance: () => {
      return echartsInstance
    }
  }))

  const chartsRelativeSize = (percent, derection) => {
    let windowW = echartsInstance.offsetWidth
    let windowH = echartsInstance.offsetHeight
    let r = 0
    if (derection === 'h') {
      r = (percent * windowH) / 100
    } else {
      r = (percent * windowW) / 100
    }
    return r
  }

  const labelOption = {
    show: true,
    // position: app.config.position,
    // distance: app.config.distance,
    // align: app.config.align,
    // verticalAlign: app.config.verticalAlign,
    // rotate: app.config.rotate,
    formatter: '{c}  {name|{a}}',
    fontSize: 16,
    rich: {
      name: {}
    }
  }

  const setOptions = () => {
    let charList = []
    // eslint-disable-next-line array-callback-return
    data?.xContentInfoVos?.map((xItem) => {
      if (xItem.content !== '总计') {
        let xCharData = data?.yContentInfoVos?.map((yItem) => {
          // let chartData = []
          let chartItem = data?.statisticsInfoVos.filter((filterItem) => {
            return filterItem.xKey === xItem.key && filterItem.yKey === yItem.key
          })[0]
          return parseFloat(chartItem.proportion)
        })

        charList.push({
          name: xItem.content,
          data: xCharData,
          type: 'bar',
          // barWidth: 23
          // barGap: 0.2,
          barWidth: chartsRelativeSize(0.8, 'r')
          // itemStyle: {
          //   normal: {
          //     show: true,
          //     barBorderRadius: chartsRelativeSize(1.1, 'r')
          //   }
          // },
        })
      } else {
        return null
      }
    })

    echartsInstance.setOption({
      title: {
        top: chartsRelativeSize(2, 'r'),
        left: chartsRelativeSize(1, 'r'),
        textStyle: {
          color: '#F0BF04',
          fontSize: chartsRelativeSize(0.7, 'r')
        }
      },
      tooltip: {
        trigger: 'axis'
        //   formatter: function (params) {
        //     let arr = [];
        //     params.forEach(function (item, index) {
        //       let N = item.seriesName;
        //       let V = '';
        //       if (item.value > 100000000) {// 亿
        //         V += (item.value / 100000000).toFixed(1) + '亿';
        //       } else if (item.value > 10000) {// 万
        //         V += (item.value / 10000).toFixed(1) + '万';
        //       } else {
        //         V += item.value;
        //       }
        //       let a = { name: N, value: V };
        //       arr.push(a);
        //     });
        //     let num = '';
        //     arr.forEach(function (item, index) {
        //       num += item.name + ":" + item.value + "<br/>";
        //     });
        //     return params[0].name + "<br>" + num;
        //   }
      },
      legend: {
        type: 'scroll',
        data: data?.xContentInfoVos
          ?.map((item) => {
            if (item.content !== '总计') {
              return item.content
            } else {
              return null
            }
          })
          .filter((item) => item !== null),
        bottom: 0
      },
      // toolbox: {
      //   show: true,
      //   orient: 'vertical',
      //   left: 'right',
      //   top: 'center',
      //   feature: {
      //     mark: { show: true },
      //     dataView: { show: true, readOnly: false },
      //     magicType: { show: true, type: ['line', 'bar', 'stack'] },
      //     restore: { show: true },
      //     saveAsImage: { show: true }
      //   }
      // },
      // dataZoom: [
      //   {
      //     type: 'slider',
      //     show: true,
      //     xAxisIndex: [0],
      //     left: '9%',
      //     bottom: -5,
      //     start: 10,
      //     end: 90 // 初始化滚动条
      //   }
      // ],
      xAxis: [
        {
          type: 'category',
          // axisTick: { show: false },
          axisLabel: {
            textStyle: {
              // color: '#fff',// 坐标值得具体的颜色
            },
            formatter: function (params) {
              let newParamsName = '' // 最终拼接成的字符串
              let paramsNameNumber = params.length // 实际标签的个数
              let provideNumber = 3 // 每行能显示的字的个数
              let rowNumber = Math.ceil(paramsNameNumber / provideNumber) // 计算行数，向上取整
              // 判断是否需要换行
              if (paramsNameNumber > provideNumber) {
                // 循环得到每行的显示内容，p代表行
                for (let p = 0; p < rowNumber; p++) {
                  let tempStr = '' // 表示每一次截取的字符串
                  let start = p * provideNumber // 开始截取的位置
                  let end = start + provideNumber // 结束截取的位置
                  if (p === rowNumber - 1) {
                    // 最后一次不换行
                    tempStr = params.substring(start, paramsNameNumber)
                  } else {
                    // 每一次拼接字符串并换行
                    tempStr = params.substring(start, end) + '\n'
                  }
                  newParamsName += tempStr // 最终拼成的字符串
                }
              } else {
                // 将旧标签的值赋给新标签
                newParamsName = params
              }
              return newParamsName
            },
            interval: 0
          },
          data: data?.yContentInfoVos
            ?.map((item) => {
              if (item.content !== '总计') {
                return item.content
              } else {
                return null
              }
            })
            .filter((item) => item !== null)
        }
      ],
      yAxis: [
        {
          type: 'value',
          axisLabel: {
            textStyle: {
              // color: '#fff',// 坐标值得具体的颜色
            },
            formatter: function (params) {
              let newParamsName = '' // 最终拼接成的字符串
              newParamsName = params + '%'
              return newParamsName
            },
            interval: 0
          }
        }
      ],
      series: charList
    })
  }

  return (
    <div className="strip-cross-multi-bar-chart" id={chartId || 'strip-cross-multi-bar-chart'} />
  )
}
export default (CrossMultiBarChart)
